package com.bestcem.xm.txtanls.algorithm;

import com.bestcem.xm.common.core.algorithm.BinaryId;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * 分表逻辑抽象
 *
 * @author lee
 * @dete 2022-09-27 13:04:14
 */
public interface TxtanlsSharding {

    /**
     * 分表操作抽象
     *
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    default String sharding(Collection<String> availableTargetNames, PreciseShardingValue<BinaryId> shardingValue) {
        String logicTableName = shardingValue.getLogicTableName();
        if (availableTargetNames.isEmpty()) {
            throw new UnsupportedOperationException("actual-data-nodes is not support, please check your config");
        }
        int shardCount = availableTargetNames.size();
        // 分片key
        BinaryId binaryId = shardingValue.getValue();
        int databaseIndex = binaryId.hashCode() & (shardCount - 1);
        // 数据库中对应的真实表
        String realTableName = logicTableName + "_" + databaseIndex;
        if (availableTargetNames.contains(realTableName)) {
            return realTableName;
        }
        throw new UnsupportedOperationException("route " + realTableName + " is not support, please check your config");
    }
}
